package com.nf.health.app.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.models.BluetoothDeviceAttr;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.service.SampleGattAttributes;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bluetools.ProtocolParser;

@SuppressLint("NewApi")
/**
 * 尿检，血糖，血压,体脂四种设备蓝牙连接公共页面
 * @author jiax
 *
 */
public class HealthyDataFragment extends IBaseFragment implements
		SensorEventListener {
	protected static final String TAG = HealthyDataFragment.class
			.getSimpleName();

	private ImageView shake_bg;
	private TextView tv_shake_title;
	private SensorManager mSensorManager;
	private Vibrator mVibrator;
	private String mDeviceAddress = "";
	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback;
	private BluetoothAdapter mBluetoothAdapter;
	// 蓝牙服务类
	private BluetoothLeService mBluetoothLeService;
	private Handler mHandler = new Handler();
	private ServiceConnection mServiceConnection;
	private Runnable runnable;
	/**
	 * 标记震动传感器是否再次监听
	 */
	private boolean flg = true;
	private View rl_shake;
	private View ll_blood_sugar;
	private TextView tv_sugar;
	private View btn_commint_blood_sugar;
	private String result;
	private String currentDeviceName;
	private String notifyUUID;
	private String writeUUID;
	private String serviceUUID;
	private String type;

	/**
	 * Handles various events fired by the Service. 接收蓝牙服务传入的事件消息，或者是接收到的蓝牙数据
	 */
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				if (DeviceData.Type.URINE.equals(type)) {
					tv_shake_title.setText("请点击“检测”进行测量");
				}else if(DeviceData.Type.BLOOD_SUGAR.equals(type)){
					tv_shake_title.setText("请将试纸插入卡槽");
				} else {
					tv_shake_title.setText("蓝牙已连接");
				}
				flg = false;// 取消连接
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				tv_shake_title.setText("蓝牙连接断开,请重试");
				flg = true;
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
				try {
					displayGattServices(mBluetoothLeService
							.getSupportedGattServices());
				} catch (Exception e) {
					LogUtil.exception(e);
				}
			} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				byte[] data = intent
						.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);

				if (data == null) {
					LogUtil.i(TAG, "数据暂时为空");
					return;
				}
				try {
					if (DeviceData.Type.BLOOD_SUGAR.equals(type)) {
						handleBloodSugarResult(data);
					} else if (DeviceData.Type.BLOOD_PRESSURE.equals(type)) {
						handleBloodPressureData(data);
					} else if (DeviceData.Type.URINE.equals(type)) {
						handleUrineResult(data);
					} 
				} catch (Exception e) {
					LogUtil.exception(e);
				}
			}
		}
	};
	private View ll_urine;
	private TextView tv_putaotang;
	private TextView tv_danhongsu;
	private TextView tv_dongti;
	private TextView tv_bizhong;
	private TextView tv_hongxibao;
	private TextView tv_ph;
	private TextView tv_niaodanbai;
	private TextView tv_niaodanyuan;
	private TextView tv_yaxiaosuanyan;
	private TextView tv_baixibao;
	private String putaotangValue;
	private String danhongsuVlaue;
	private String dongtiValue;
	private String bizhongValue;
	private String hongxibaoValue;
	private String phValue;
	private String niaodanbaiValue;
	private String niaodanyuanValue;
	private String yaxiaosuanyanValue;
	private String baixibaoValue;

	private View ll_blood_pressure;
	private TextView tv_high_pressure;
	private TextView tv_low_pressure;
	private TextView tv_heart_rate;
	private int highPressure;
	private int lowPressure;
	private int heartRate;

	private int age;
	private int height;
	private float weight;
	private int fat;
	private int bone = 0;
	private int jiRou;
	private int piXiaZhiFang;
	private int shuiFen;
	private int bMR;
	private TextView tv_height, tv_weight, tv_fat, tv_bone, tv_jiroulv, tv_subCutaneousFat, tv_waterContent, tv_calorie, tv_age;

	private StringBuilder sb;
	private String urineData = new String();
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		type = getArguments().getString("type");
		addViewFillInRoot(R.layout.fragment_data_auto_input);
		initView();
		try {
			initBluetooth();
		} catch (Exception e) {
		}
	}

	public static HealthyDataFragment getInstance(String type){
		Bundle bundle = new Bundle();  
        bundle.putString("type", type);  
        HealthyDataFragment fragment = new HealthyDataFragment();  
        fragment.setArguments(bundle);  
        return fragment;
	}
	
	/**
	 * 初始化不通类型的View
	 */
	private void initView() {
		tv_shake_title = (TextView) rootView.findViewById(R.id.tv_shake_title);
		shake_bg = (ImageView) rootView.findViewById(R.id.shake_bg);
		rl_shake = ViewUtil.getView(rootView, R.id.rl_shake);
		if (DeviceData.Type.BLOOD_SUGAR.equals(type)) {
			currentDeviceName = BluetoothDeviceAttr.BLOOD_SUGAR_DEVICE_NAME;
			serviceUUID = SampleGattAttributes.BloodSugar.SERVICE_UUID;
			notifyUUID = SampleGattAttributes.BloodSugar.NOTIFY_UUID;

			ll_blood_sugar = ViewUtil.getView(rootView, R.id.ll_blood_sugar);
			tv_sugar = ViewUtil.getView(rootView, R.id.tv_sugar);
			btn_commint_blood_sugar = ViewUtil.getView(rootView,
					R.id.btn_commint_blood_sugar);
			btn_commint_blood_sugar.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					provider.requestAddDeviceGlucose(result, "", "addSugar");
				}
			});

		} else if (DeviceData.Type.BLOOD_PRESSURE.equals(type)) {
			currentDeviceName = BluetoothDeviceAttr.BLOOD_PRESSURE_DEVICE_NAME;
			serviceUUID = SampleGattAttributes.BloodPressure.SERVICE_UUID;
			writeUUID = SampleGattAttributes.BloodPressure.WRITE_UUID;
			notifyUUID = SampleGattAttributes.BloodPressure.NOTIFY_UUID;

			ll_blood_pressure = ViewUtil.getView(rootView,
					R.id.ll_blood_pressure);
			View btn_commit_blood_pressure = ViewUtil.getView(rootView,
					R.id.btn_commit_blood_pressure);
			tv_high_pressure = ViewUtil
					.getView(rootView, R.id.tv_high_pressure);
			tv_low_pressure = ViewUtil.getView(rootView, R.id.tv_low_pressure);
			tv_heart_rate = ViewUtil.getView(rootView, R.id.tv_heart_rate);

//			btn_commit_blood_pressure.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//					provider.requestAddDeviceBlood(
//							String.valueOf(highPressure),
//							String.valueOf(lowPressure),
//							String.valueOf(heartRate), "addBloodPressure");
//				}
//			});

		} else if (DeviceData.Type.URINE.equals(type)) {
			currentDeviceName = BluetoothDeviceAttr.URINE_DEVICE_NAME;
			serviceUUID = SampleGattAttributes.Urine.SERVICE_UUID;
			notifyUUID = SampleGattAttributes.Urine.NOTIFY_UUID;

			ll_urine = ViewUtil.getView(rootView, R.id.ll_urine);
			Button btn_commit_urine = ViewUtil.getView(rootView,
					R.id.btn_commit_urine);
			tv_putaotang = ViewUtil.getView(rootView, R.id.tv_putaotang);
			tv_danhongsu = ViewUtil.getView(rootView, R.id.tv_danhongsu);
			tv_dongti = ViewUtil.getView(rootView, R.id.tv_dongti);
			tv_bizhong = ViewUtil.getView(rootView, R.id.tv_bizhong);
			tv_hongxibao = ViewUtil.getView(rootView, R.id.tv_hongxibao);
			tv_ph = ViewUtil.getView(rootView, R.id.tv_ph);
			tv_niaodanbai = ViewUtil.getView(rootView, R.id.tv_niaodanbai);
			tv_niaodanyuan = ViewUtil.getView(rootView, R.id.tv_niaodanyuan);
			tv_yaxiaosuanyan = ViewUtil.getView(rootView, R.id.tv_yaxiaosuanyan);
			tv_baixibao = ViewUtil.getView(rootView, R.id.tv_baixibao);

			btn_commit_urine.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					provider.requestAddDeviceUrine(putaotangValue, danhongsuVlaue,
//							dongtiValue, bizhongValue, hongxibaoValue, phValue,
//							niaodanbaiValue, niaodanyuanValue,
//							yaxiaosuanyanValue, baixibaoValue, "AddDeviceUrine");
				}
			});
		}
	}

	@Override
	public void handleActionSuccess(String actionName, Object object) {
		showToast("添加成功！");
		getActivity().finish();
	}

	private void initBluetooth() {
		// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
		if (!getActivity().getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			showToast("不支持蓝牙4.0通讯");
			tv_shake_title.setText("该设备不支持蓝牙4.0通讯");
			return;
		}

		// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
		// final BluetoothManager bluetoothManager = (BluetoothManager)
		// getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// 检查设备上是否支持蓝牙
		if (mBluetoothAdapter == null) {
			showToast("设备不支持蓝牙");
			return;
		}

		mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

			@Override
			public void onLeScan(final BluetoothDevice device, int rssi,
					byte[] scanRecord) {
				if (getActivity() == null) {
					return;
				}

				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
							if (device != null && device.getName().contains(currentDeviceName)) {
								mDeviceAddress = device.getAddress();
								tv_shake_title.setText("发现设备：" + device.getName());
								// Toast.makeText(MainActivity.this,
								// "发现设备："+device.getName() + " MAC:"+
								// mDeviceAddress,
								// Toast.LENGTH_SHORT).show();
								scanLeDevice(false);
								// 执行连接的操作
								if (mBluetoothLeService == null) {
									showToast("蓝牙服务未绑定!");
									return;
								}
								if (mDeviceAddress.length() < 12) {
									showToast("没有指定设备，请先扫描!");
									return;
								}
								mBluetoothLeService.connect(mDeviceAddress);
							}
					}
				});
			}
		};

		bindLeService();
		if (!mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}

		mSensorManager = (SensorManager) getActivity().getSystemService(Service.SENSOR_SERVICE);
		mVibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mSensorManager != null) {
			mSensorManager.registerListener(this,
					mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
		getActivity().registerReceiver(mGattUpdateReceiver,
				BluetoothLeService.makeGattUpdateIntentFilter());
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mSensorManager != null) {
			mSensorManager.unregisterListener(this);
		}
		if (mGattUpdateReceiver != null) {
			getActivity().unregisterReceiver(mGattUpdateReceiver);
		}
	}

	/**
	 * 处理获取到的蓝牙数据
	 * 
	 * @param data
	 */
	private boolean isAppend = false;

	private void handleBloodPressureData(byte[] data) {
		String result = ProtocolParser.bytes2HexString(data);
		LogUtil.i(TAG, result);
		if (result.startsWith("FF")) {
			sb = new StringBuilder();
			sb.append(result);
			isAppend = true;
			return;
		}
		if (isAppend) {
			sb.append(result);
			String[] strArray = sb.toString().split("FF010100000001000C");
			// 发送3次一样的FF010100000001000C80 65 3F 48
			// 0D4516068E5551445203FE
			/**
			 * FF ， 01 01 ，00 00 00 01， 00 0C（长度）， 81（高4位CMD=0x80，低4位为用户），
			 * 64（高压）， 45（低压）， 4E（脉搏）， 0B（年）， 41（ResultDataDA）， 00（ResultDataHO）
			 * ， 01(分) ， 01 02 03 04（4Byte ID）， CF 01（CS=0x1CF）， FE（结束）
			 */
			LogUtil.i(TAG, "结果" + strArray[2]);
			flg = false;
			highPressure = Integer.parseInt(strArray[1].substring(2, 4), 16);
			lowPressure = Integer.parseInt(strArray[1].substring(4, 6), 16);
			heartRate = Integer.parseInt(strArray[1].substring(6, 8), 16);

			tv_high_pressure.setText(highPressure + "mmHg");
			tv_low_pressure.setText(lowPressure + "mmHg");
			tv_heart_rate.setText(heartRate + "次");

			ll_blood_pressure.setVisibility(View.VISIBLE);
			rl_shake.setVisibility(View.GONE);
			// TODO 停止循环
			if (mHandler != null) {
				mHandler.removeCallbacks(runnable);
			}
			return;
		}

		if ("FE8100000001FF".equals(result)) {
			tv_shake_title.setText("开机检测中...");
		} else if (result.startsWith("FE84")) {
			// 输出“测量过程”的压力值。例如0xFE 84 00 02 00 04(FE 84 PressureH PressureL 00
			// 04)
			// Pressure = PressureH * 256 + PressureL;
		} else if (result.startsWith("FE83")) {
			// 测量错误
			int code = Integer.parseInt(result.substring(5, 6));
			switch (code) {
			case 1:// 测量过程中没有侦测到脉搏信号
				showToast("测量错误");
				break;
			case 2:// 测量错误，测量过长中干扰过大
				showToast("测量错误");
				break;
			case 3:// 充气失败，充气时间过长或袖带漏气
				showToast("充气失败");
				break;
			case 5:// 测量失败，测量的结果高压与低压相差太大
				showToast("测量失败");
				break;
			default:
				LogUtil.i(TAG, "错误结果");
				break;
			}
			flg = true;
			tv_shake_title.setText("测量失败，请重试");
		}
	}

	/**
	 * 处理体脂秤
	 * 
	 * @param data
	 *            cf 11 9e a8 02a7 00000000000000000000 CF 03 98 A1 02A4
	 *            00000000000000000000
	 */
	private int count = 0;

	private void handleBalanceResult(byte[] data) {
		String msg = ProtocolParser.bytes2HexString(data);
		if (!TextUtils.isEmpty(msg)) {
			if ("fd31000000000031".equals(msg) && count <= 3) {
				count++;
				if (count == 3) {
					count = 0;
					tv_shake_title.setText("连接失败，请重试~");
				}
			} else {
				flg = false;
				String[] b = new String[(msg.length()) / 2];
				for (int i = 0; i < (msg.length()) / 2; i++) {
					b[i] = msg.trim().substring(i * 2, 2 * (i + 1));
				}
				age = Integer.parseInt(b[2], 16) & 127;
				height = Integer.parseInt(b[3], 16);
				int weightTemp = Integer.parseInt(b[4] + b[5], 16);
				fat = Integer.parseInt(b[6] + b[7], 16);
				bone = Integer.parseInt(b[8], 16);
				jiRou = Integer.parseInt(b[9] + b[10], 16);
				piXiaZhiFang = Integer.parseInt(b[11], 16);
				shuiFen = Integer.parseInt(b[12] + b[13], 16);
				bMR = Integer.parseInt(b[14] + b[15], 16);
				tv_height.setText(height + " CM");
				weight = weightTemp / 10.0f;
				tv_weight.setText(weight + " KG");
				tv_fat.setText(fat + "%");
				tv_bone.setText(bone + " %");
				tv_jiroulv.setText(jiRou + "%");
				tv_subCutaneousFat.setText(piXiaZhiFang + " mm");
				tv_waterContent.setText(shuiFen + " ppm");
				tv_calorie.setText(bMR + " KG");
				if (age == 10) {
					tv_age.setText("小于" + age + " 岁");
				} else {
					tv_age.setText(age + " 岁");
				}
			}
		}
	}

	/**
	 * FEE10000000500 比如报头FE E1， FE是报文头，E1表示尿机，E2表示血压计，E3表示血糖仪，E4表示体重计，,最终蓝牙输出：
	 * FE E1 03 00 00 ** ** ** ** 00 00 04这样一组12位的数据。
	 * 例如诊断数据：3005040004表示为，葡萄糖（++），胆红素（-），酮体（-），比重（1.030），红细胞 （-），
	 * pH（7.0），尿蛋白（-），尿胆原（-），亚硝酸盐（-），白细胞（+++）以此类推。注意顺序，先从葡萄糖开始——>白细胞
	 * 
	 * @param data
	 */
	private void handleUrineResult(byte[] data) {
		String str = Util.toStringHex(ProtocolParser.bytes2HexString(data));
		if (!TextUtils.isEmpty(str)) {
			urineData += str;
		}
		if (urineData != null && urineData.length() == 35
				&& urineData.contains(" ")) {
			LogUtil.i(TAG, str);
			String result = urineData.replace(" ", "");
			int index = 5;
			int putaotangIndex = Integer.parseInt(result.substring(index,
					++index));
			int danhongsuIndex = Integer.parseInt(result.substring(++index,
					++index));
			int dongtiIndex = Integer.parseInt(result.substring(++index,
					++index));
			int bizhongIndex = Integer.parseInt(result.substring(++index,
					++index));
			int hongxibaoIndex = Integer.parseInt(result.substring(++index,
					++index));
			int phIndex = Integer.parseInt(result.substring(++index, ++index));
			int niaodanbaiIndex = Integer.parseInt(result.substring(++index,
					++index));
			int niaodanyuanIndex = Integer.parseInt(result.substring(++index,
					++index));
			int yaxiaosuanyanIndex = Integer.parseInt(result.substring(++index,
					++index));
			int baixibaoIndex = Integer.parseInt(result.substring(++index,
					++index));
			putaotangValue = BluetoothDeviceAttr.valueArray[putaotangIndex];
			danhongsuVlaue = BluetoothDeviceAttr.valueArray[danhongsuIndex];
			dongtiValue = BluetoothDeviceAttr.valueArray[dongtiIndex];
			bizhongValue = BluetoothDeviceAttr.scaleArray[bizhongIndex];
			hongxibaoValue = BluetoothDeviceAttr.valueArray[hongxibaoIndex];
			phValue = BluetoothDeviceAttr.phArray[phIndex];
			niaodanbaiValue = BluetoothDeviceAttr.valueArray[niaodanbaiIndex];
			niaodanyuanValue = BluetoothDeviceAttr.niaoDanYuanArray[niaodanyuanIndex];
			yaxiaosuanyanValue = BluetoothDeviceAttr.valueArray[yaxiaosuanyanIndex];
			baixibaoValue = BluetoothDeviceAttr.valueArray[baixibaoIndex];

			tv_putaotang.setText(putaotangValue);
			tv_danhongsu.setText(danhongsuVlaue);
			tv_dongti.setText(dongtiValue);
			if (bizhongIndex == 5) {
				tv_bizhong.setText(">=" + bizhongValue);
			} else {
				tv_bizhong.setText(bizhongValue);
			}
			tv_hongxibao.setText(hongxibaoValue);
			tv_ph.setText(phValue);
			tv_niaodanbai.setText(niaodanbaiValue);
			if (niaodanyuanIndex == 0) {
				tv_niaodanyuan.setText("<=" + niaodanyuanValue + "EU/dL");
			} else {
				tv_niaodanyuan.setText(niaodanyuanValue + "EU/dL");
			}
			tv_yaxiaosuanyan.setText(yaxiaosuanyanValue);
			tv_baixibao.setText(baixibaoValue);

			ll_urine.setVisibility(View.VISIBLE);
			rl_shake.setVisibility(View.GONE);
			// TODO 停止循环
			if (mHandler != null) {
				urineData = null;
				mHandler.removeCallbacks(runnable);
			}
		}
	}

	/**
	 * 处理输出结果及页面显示 连机命令：0xFE 6B 75 5A 55 AA BB CC 滴血命令：0xFE 6B 75 5A 55 BB BB CC
	 * 倒数时间显示：0xFE 6B 75 5A 55 time BB time time(5,4,3,2,1) 结果命令：0xFE 6A 75 5A
	 * Highbyte Lowbyte 88 CKS CKS=FE+ 6A+75+5A+00+FB+88=0X3BA 取低8位 CKS=0xBA
	 * 
	 * @param data
	 */
	@SuppressLint("DefaultLocale")
	private void handleBloodSugarResult(byte[] data) {

		String str = ProtocolParser.bytes2HexString(data);
		LogUtil.i(TAG, str);
		if (str.contains("AABBCC")) {
			tv_shake_title.setText("连接设备成功");
		} else if (str.contains("BBBBCC")) {
			tv_shake_title.setText("请滴血进行测量");
		} else if (str.contains("BB")) {

			String ms = str.substring(11, 12);

			tv_shake_title.setText("倒计时" + ms + "秒");
		} else {
			// 将data数组转为十六进制，再转int相加，取低8位
			int count = 0;
			int countOld = 0;//记录旧设备的值
			for (int i = 0; i < str.length() - 2; i = i + 2) {
				int parseInt = Integer.parseInt(str.substring(i, i + 2), 16);
				count += parseInt;
				if(i!=0){
					countOld += parseInt;
				}
			}
			String hexString = Integer.toHexString(count).toUpperCase();
			String hexStringOld = Integer.toHexString(countOld).toUpperCase();
			if (hexString.contains(str.substring(str.length() - 2,
					str.length()))||hexStringOld.contains(str.substring(str.length() - 2,
							str.length()))) {
				float date = (float) (data[4] * 0x100 + data[5]);
				float aa = date / 18.0f;
				DecimalFormat decimalFormat = new DecimalFormat(".0");// 构造
				result = decimalFormat.format(aa);

				tv_sugar.setText(result + "mmol");
				ll_blood_sugar.setVisibility(View.VISIBLE);

				rl_shake.setVisibility(View.GONE);
				// TODO 停止循环
				if (mHandler != null) {
					mHandler.removeCallbacks(runnable);
				}
			}else{
				tv_shake_title.setText("数据检测失败，请重试");
				flg = true;
			}
		}
	}

	/**
	 * 根据UUID查找对应BLE
	 * 
	 * @param gattServices
	 */
	private void displayGattServices(List<BluetoothGattService> gattServices) {
		if (gattServices == null)
			return;
		String uuid = null;
		// Loops through available GATT Services.
		for (BluetoothGattService gattService : gattServices) {
			// 获取服务列表
			uuid = gattService.getUuid().toString();
			LogUtil.i(TAG, "gattService>>>"+uuid);
			if (uuid.equals(serviceUUID)) {
				// 从当前循环所指向的服务中读取特征值列表
				List<BluetoothGattCharacteristic> gattCharacteristics = gattService
						.getCharacteristics();
				// 对于当前循环所指向的服务中的每一个特征值
				for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
					uuid = gattCharacteristic.getUuid().toString();
					LogUtil.i(TAG, "gattCharacteristic>>>"+uuid);
					if (uuid.equals(notifyUUID)) {
						runnable = new Runnable() {
							@Override
							public void run() {
								if (mBluetoothLeService != null) {
									// 要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
									mBluetoothLeService.readCharacteristic(gattCharacteristic);
									// 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
									mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
									mHandler.postDelayed(this, 2000);
								}
							}
						};
						mHandler.postDelayed(runnable, 1000);
					}else if (uuid.equals(writeUUID)){
						if (currentDeviceName.equals(BluetoothDeviceAttr.BLOOD_PRESSURE_DEVICE_NAME)) {
							gattCharacteristic.setValue(getStartCommand());
							mBluetoothLeService.writeCharacteristic(gattCharacteristic);
							tv_shake_title.setText("开机检测中...");
						} 
					}
				}
			}
		}
	}
	/**
	 * 设置12小时制还是24小时制
	 * @param is24H
	 */
	public byte[] setTime(boolean is24H){
		byte[] b = new byte[5];
		b[0] = (byte) 0x6E;
		b[1] = (byte) 0x01;
		b[2] = (byte) 0x34;
		if(is24H){
			b[3] = (byte) 0x00;
		}else{
			b[3] = (byte) 0x01;
		}
		b[4] = (byte) 0x8F;
		return b;
	}
	
	@SuppressLint("SimpleDateFormat")
	public byte[] setSyncTime(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String[] timeArray = format.format(new Date()).split("-");
		StringBuffer sb = new StringBuffer();
		sb.append("6E0115");
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[0].substring(2, 4))));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[0].substring(0, 2))));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[1])));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[2])));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[3])));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[4])));
		sb.append(Util.toHexStr(Integer.parseInt(timeArray[5])));
		sb.append("8F");
		LogUtil.i(TAG, sb.toString());
		return Util.hexStringToBytes(sb.toString());
	}
	
	/**
	 * 写入的指令数据 测试指令FE 03 01 00 AA 19 01 B0 byte[7] = byte[1]^....byte[6] 异或
	 * 
	 * @return
	 */
	@SuppressLint("SimpleDateFormat")
	public byte[] getByteData() {
		String sex = PreferenceHelper.getString(PreferenceHelper.USERSEX, "1");
		String height = PreferenceHelper.getString(PreferenceHelper.USERHEIGHT,
				"170");
		double doubleH = Double.parseDouble(height);
		int intH = (int) doubleH;		byte[] b = new byte[8];
		b[0] = (byte) 0xfe;// 包头
		b[1] = (byte) 0x03;
		if (sex.equals("1")) {// 性别
			b[2] = (byte) 0x01;
		} else {
			b[2] = (byte) 0x00;
		}
		b[3] = (byte) 0x00;// 0普通 1业余 2专业
		b[4] = Integer.valueOf(intH).byteValue();// 身高
		try {
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
			Date date = s.parse(PreferenceHelper.getString(
					PreferenceHelper.BIRTHDAY, "1991-01-01"));
			int age = Util.getAgeByBirthday(date);
			if (age < 10) {
				age = 10;
			}
			b[5] = Integer.valueOf(age).byteValue();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// b[4] = (byte) 0xaa;
		// b[5] = (byte) 0x19;
		b[6] = (byte) 0x01;// 单位 01千克 02lb(英石) 03ST:LB(英磅)
		b[7] = (byte) (b[1] ^ b[2] ^ b[3] ^ b[4] ^ b[5] ^ b[6]);
		return b;
	}

	/**
	 * 获取开机指令
	 * 
	 * @return
	 */
	public byte[] getStartCommand() {
		// 血压计开机下发送指令：0xfe,0x81,0x00,0x00,0x00,0x01
		// 关机指令：0xfe,0x82,0x00,0x00,0x02,0xFF
		// 错误指令：0xfe,0x83,ResultCode,0x00,0x00,0x03
		// ResultCode=1：测量过程中没有侦测到脉搏信号。
		// ResultCode=2：测量错误，测量过长中干扰过大。
		// ResultCode=3：充气失败，充气时间过长或袖带漏气。
		// ResultCode=5：测量失败，测量的结果高压与低压相差太大。
		byte[] b = new byte[6];
		b[0] = (byte) 0xfe;// 包头
		b[1] = (byte) 0x81;
		b[2] = (byte) 0x00;
		b[3] = (byte) 0x00;
		b[4] = (byte) 0x00;
		b[5] = (byte) 0x01;
		return b;
	}

	/**
	 * 绑定蓝牙服务和广播，Activity初始化需绑定蓝牙服务。
	 */
	public void bindLeService() {
		mServiceConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName componentName,
					IBinder service) {
				mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
						.getService();
				if (!mBluetoothLeService.initialize()) {
					LogUtil.e(TAG, "Unable to initialize Bluetooth");
				}
			}

			@Override
			public void onServiceDisconnected(ComponentName componentName) {
				mBluetoothLeService = null;
			}
		};

		Intent bleService = new Intent(getActivity(), BluetoothLeService.class);
		getActivity().bindService(bleService, mServiceConnection,
				Context.BIND_AUTO_CREATE);
	}

	@SuppressWarnings("deprecation")
	private void scanLeDevice(final boolean enable) {
		if (enable) {

			// Stops scanning after a pre-defined scan period.
			// mHandler.postDelayed(new Runnable() {
			// @Override
			// public void run() {
			// if(TextUtils.isEmpty(mDeviceAddress)){
			// mBluetoothAdapter.stopLeScan(mLeScanCallback);
			// tv_shake_title.setText("扫描设备失败，请重试");
			// }
			// }
			// }, 120000);
			tv_shake_title.setText("设备扫描中...");
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			try {
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
			} catch (Exception e) {
			}
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER && flg) {
			if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14
					|| Math.abs(values[2]) > 14) {
				long[] pattern = { 500, 1000 };
				mVibrator.vibrate(pattern, -1);

				ObjectAnimator animator = ObjectAnimator.ofFloat(shake_bg,
						"translationX", 0, 100);
				animator.setRepeatCount(3);
				animator.setRepeatMode(ObjectAnimator.REVERSE);
				animator.start();
				animator.addListener(new Animator.AnimatorListener() {

					@Override
					public void onAnimationStart(Animator arg0) {
						flg = false;
					}

					@Override
					public void onAnimationRepeat(Animator arg0) {

					}

					@Override
					public void onAnimationEnd(Animator arg0) {
						flg = true;
					}

					@Override
					public void onAnimationCancel(Animator arg0) {

					}
				});
				scanLeDevice(false);
				if(TextUtils.isEmpty(mDeviceAddress)){
					scanLeDevice(true);
				}else{
					tv_shake_title.setText("连接中...");
					mBluetoothLeService.connect(mDeviceAddress);
				}
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onDestroy() {
		if (mHandler != null && runnable != null) {
			mHandler.removeCallbacks(runnable);
		}
//		if (mBluetoothAdapter != null) {
//			mBluetoothAdapter.disable();
//		}
		unbindService();
		super.onDestroy();
	}

	/**
	 * 取消绑定蓝牙服务和广播
	 */
	public void unbindService() {
		if (mServiceConnection != null) {
			getActivity().unbindService(mServiceConnection);
		}
		mBluetoothLeService.close();
		mBluetoothLeService = null;
	}

	public void stopShake() {
		flg = false;
	}

	public void startShake() {
		if (rl_shake == null) {
			return;
		}
		flg = rl_shake.getVisibility() != View.GONE;
	}

}
